﻿namespace IntellectShop.Web2.Controllers
{
	using System;
	using System.Collections.Generic;
	using System.IO;
	using System.Text;
	using System.Web;
	using System.Web.Mvc;
	using System.Xml;
	using IntellectShop.Common;
	using IntellectShop.Web2.ViewModels;

	[IntellectShop.Web2.Code.NoCache]
	[IntellectShop.Web2.Code.HandleErrorWithELMAH]
	[ValidateInputAttribute(false)]
	public class CourseController : Controller
	{
		public ActionResult Browse(string categoryID)
		{
			int id = Int32.Parse(categoryID);
			Common.Category category = Common.Category.RetrieveByID(id);
			if (category == null)
				throw new HttpException(404, "Page not found");

			var viewModel = new CategoryBrowseCourseViewModel
			{
				Category = category,
				Courses = Common.Course.RetrieveCoursesByCategoryID(id)
			};

			return View(viewModel);
		}

		public ActionResult CategoryIndex()
		{
			List<Common.Category> categories = Common.Course.RetrieveCategoriesHavingCourses();

			var viewModel = new StoreCategoryIndexViewModel
			{
				NumberOfCategories = categories.Count,
				Categories = categories
			};

			return View(viewModel);
		}

		public ActionResult Details(int id)
		{
			var course = Common.Course.RetrieveByCommodityID(id);
			if (course == null)
				throw new HttpException(404, "Page not found");

			return View(course);
		}

		public ActionResult Index()
		{
			var viewModel = new CourseIndexViewModel
			{
				Courses = Common.Course.RetrieveCoursesByCategory()
			};

			return View(viewModel);
		}

		[Authorize(Roles = Globals.AdministratorRoleName)]
		public ActionResult Create()
		{
			var viewModel = new CourseEditViewModel
			{
				Categories = Common.Category.RetrieveAll(),
				Course = new Common.Course()
			};

			return View(viewModel);
		}

		[Authorize(Roles = Globals.AdministratorRoleName)]
		[HttpPost]
		public ActionResult Create(Common.Course course)
		{
			try
			{
				if (!ModelState.IsValid)
					throw new ArgumentException("Ошибка при заполнении полей для: Course!");

				course.Create(HttpContext.User.Identity.Name);
				return RedirectToAction("Index");
			}
			catch (Exception e)
			{
				var viewModel = new CourseEditViewModel
				{
					Categories = Common.Category.RetrieveAll(),
					Course = course,
					Message = e.Message
				};

				return View(viewModel);
			}
		}

		[Authorize(Roles = Globals.AdministratorRoleName)]
		public ActionResult Edit(int id)
		{
			var course = Common.Course.RetrieveByCommodityID(id);
			if (course == null)
				throw new HttpException(404, "Page not found");

			var viewModel = new CourseEditViewModel
			{
				Categories = Common.Category.RetrieveAll(),
				Course = course
			};

			return View(viewModel);
		}

		[Authorize(Roles = Globals.AdministratorRoleName)]
		[HttpPost]
		public ActionResult Edit(int id, FormCollection collection)
		{
			var course = Common.Course.RetrieveByCommodityID(id);
			if (course == null)
				throw new HttpException(404, "Page not found");

			try
			{
				if (!ModelState.IsValid)
					throw new ArgumentException("Ошибка при заполнении полей для: Course!");

				UpdateModel(course, "Course");
				course.Update(HttpContext.User.Identity.Name);
				return Redirect(Url.RouteUrl(new { action = "Index" }) + "#id" + id);
			}
			catch (Exception e)
			{
				var viewModel = new CourseEditViewModel
				{
					Course = course,
					Categories = Common.Category.RetrieveAll(),
					Message = e.Message
				};

				return View(viewModel);
			}
		}

		[Authorize(Roles = Globals.AdministratorRoleName)]
		public ActionResult Delete(int courseID)
		{
			var course = Common.Course.RetrieveByCourseID(courseID);
			if (course == null)
				throw new HttpException(404, "Page not found");
			var viewModel = new CourseRemoveViewModel()
			{
				Course = course
			};

			return View(viewModel);
		}

		[Authorize(Roles = Globals.AdministratorRoleName)]
		[HttpPost]
		public ActionResult Delete(int courseID, FormCollection collection)
		{
			var course = Common.Course.RetrieveByCourseID(courseID);
			if (course == null)
				throw new HttpException(404, "Page not found");

			try
			{
				if (!ModelState.IsValid)
					throw new ArgumentException("Ошибка при заполнении полей для: Course!");

				Common.Course.Delete(courseID);
				return RedirectToAction("Index");
			}
			catch (Exception e)
			{
				var viewModel = new CourseRemoveViewModel()
				{
					Course = course,
					Message = e.Message
				};

				return View(viewModel);
			}
		}

		[Authorize(Roles = Globals.AdministratorRoleName)]
		[AcceptVerbs(HttpVerbs.Get)]
		public ActionResult ExportXml()
		{
			string filename = "Courses.xml";
			string contentDisposition = String.Format("attachment; filename={0};", filename);

			Response.Clear();
			Response.ContentType = "application/xml";
			Response.AppendHeader("Content-Disposition", contentDisposition);

			XmlDocument doc = IntellectShop.Common.Course.ExportToXml();
			using (MemoryStream outStream = new MemoryStream())
			{
				using (XmlTextWriter writer = new XmlTextWriter(outStream, Encoding.UTF8))
				{
					writer.Formatting = Formatting.Indented;
					writer.Indentation = 1;
					writer.IndentChar = '\t';
					doc.Save(writer);

					return File(outStream.ToArray(), "application/xml");
				}
			}
		}
	}
}
